package me.zingon.yourbatis.db;

import java.sql.Connection;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class DBConnection{

    private Connection connection;
    private AtomicBoolean isBusy;
    private AtomicReference<Thread> currentThread;

    public DBConnection(Connection connection) {
        this.connection = connection;
        this.isBusy=new AtomicBoolean(false);
        this.currentThread=new AtomicReference<>();
    }

    public Connection getConnection(){
        //可重入锁
        if(isBusy.compareAndSet(false,true) || currentThread.get().equals(Thread.currentThread())){
            currentThread.set(Thread.currentThread());
            return this.connection;
        }
        return null;
    }

    public void release(){
        isBusy.compareAndSet(true,false);
    }

}
